package com.lagou.edu.ad.remote;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.edu.util.ConvertUtil;
import com.google.common.collect.Lists;
import com.lagou.edu.ad.common.PromotionAdStatusEnum;
import com.lagou.edu.ad.entity.PromotionAd;
import com.lagou.edu.dto.PromotionAdDTO;
import com.lagou.edu.dto.PromotionSpaceDTO;
import com.lagou.edu.ad.entity.PromotionSpace;
import com.lagou.edu.ad.service.IPromotionAdService;
import com.lagou.edu.ad.service.IPromotionSpaceService;
import com.lagou.edu.remoteservice.AdRemoteService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author felix
 * @since 2021-08-04
 */
@RestController
@RequestMapping("/ad")
public class PromotionAdRemoteService  {


    @Resource
    private IPromotionSpaceService promotionSpaceService;

    @Resource
    private IPromotionAdService promotionAdService;

    @RequestMapping("/space/getAllSpaces")
    public List<PromotionSpaceDTO> getAllSpaces() {
        List<PromotionSpace> promotionSpaceList = promotionSpaceService.list();
        return ConvertUtil.convertList(promotionSpaceList,PromotionSpaceDTO.class);
    }


    /**
     * 根据 spaceKey 查 广告信息
     * @param spaceKey
     * @return
     */
    @GetMapping("/space/getAdBySpaceKey")
    public List<PromotionSpaceDTO> getAdBySpaceKey(String[] spaceKey) {
        if (spaceKey == null) {
            return null;
        }

        List<PromotionSpaceDTO> list = Lists.newArrayList();

        for (String key : spaceKey) {
            LambdaQueryWrapper<PromotionSpace> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PromotionSpace::getSpaceKey,key);
            PromotionSpace promotionSpace = promotionSpaceService.getOne(wrapper);
            if (Objects.isNull(promotionSpace)) {
                continue;
            }
            PromotionSpaceDTO promotionSpaceDTO = ConvertUtil.convert(promotionSpace, PromotionSpaceDTO.class);

            LambdaQueryWrapper<PromotionAd> adWrapper = new LambdaQueryWrapper<>();
            adWrapper.eq(PromotionAd::getSpaceId,promotionSpace.getId())
                    .eq(PromotionAd::getStatus, PromotionAdStatusEnum.ONLINE.getCode());

            List<PromotionAdDTO> promotionAdDTOs = ConvertUtil.convertList(promotionAdService.list(adWrapper), PromotionAdDTO.class);
            if(!CollectionUtils.isEmpty(promotionAdDTOs)) {
                promotionSpaceDTO.setPromotionAdDTOList(promotionAdDTOs);
            }
            list.add(promotionSpaceDTO);
        }
        
        return list;
    }
}
